package com.android.volley.socket;

import com.android.volley.Network;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
 *
 */
public class SocketNetwork implements Network {

    private SocketStack mStack;
    private SocketAddressSwitcher switcher;

    public SocketNetwork(String configPath){
        switcher = new SocketAddressSwitcher(configPath);
        mStack = new SocketStack(switcher);
    }

    @Override
    public NetworkResponse performRequest(Request<?> request) throws VolleyError {
//        long requestStart = SystemClock.elapsedRealtime();

        try {
            byte[] data = mStack.performRequest(request);

//            return new NetworkResponse(200,data,null,false,SystemClock.elapsedRealtime() - requestStart);
            return new NetworkResponse(200,data,null,false,0);
        }  catch (SocketTimeoutException e) {

            switcher.onSocketTimeout();
            throw new TimeoutError();
        } catch (IOException e) {
            throw new NetworkError(e);
        }
    }


    public void performMultiRequest(MultiRequest request) throws IOException{
        Socket socket = mStack.initSocket();
        while (request.hasNext()){
            SocketStack.send(socket, request.next());
            request.onResponse(SocketStack.receive(socket));
        }
        SocketStack.closeSocket(socket);
    }


}
